package com.bjsxt.shop.common.util;

import java.util.Iterator;
import java.util.Random;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 京东的爬虫
 * @author wangshSxt
 *
 */
public class JdSplider
{
	/**
	 * 商城列表
	 * @return
	 */
	/**
	 * @return
	 */
	public JSONObject goodsList(String cat, int page)
	{
		/*
		 * 手机:https://list.jd.com/list.html?cat=9987,653,655&page=2
		 * 手机壳:https://list.jd.com/list.html?cat=9987,830,866&page=2
		 * 对讲机:https://list.jd.com/list.html?cat=9987,653,659&page=2
		 * 贴膜:https://list.jd.com/list.html?cat=9987,830,867&page=2
		 * 手机存储卡:https://list.jd.com/list.html?cat=9987,830,1099&page=2
		 * 数据线:https://list.jd.com/list.html?cat=9987,830,13661&page=2
		 * 充电器:https://list.jd.com/list.html?cat=9987,830,13660&page=2
		 * 手机耳机:https://list.jd.com/list.html?cat=9987,830,862&page=2
		 * */
		String url = "https://list.jd.com/list.html?cat=" + cat + "&"+ page ;
		System.out.println(url + "-----");
		JSONObject resultJSON = new JSONObject();
		Connection connection = Jsoup.connect(url);
		try
		{
			Document document = connection.get() ;
			/* 查找商城列表 */
			Element goodsListEle = document.getElementsByClass("gl-warp").get(0);
			Elements goodsEle = goodsListEle.getElementsByTag("li");
			
			JSONArray goodsArr = new JSONArray();
			Random random = new Random();
			int count = 0 ; 
			for (Iterator iterator = goodsEle.iterator(); iterator.hasNext();)
			{
				Element goodsEleTemp = (Element) iterator.next();
				
				try
				{
					Element nameEle = goodsEleTemp.getElementsByClass("p-name").get(0);
					String name = nameEle.text() ; 
					Element imgEle = goodsEleTemp.getElementsByClass("p-img").get(0).getElementsByTag("img").get(0);
					String imgSrc = imgEle.attr("data-lazy-img");
					
					JSONObject dataJSON = new JSONObject();
					dataJSON.put("name", name);
					dataJSON.put("imgSrc", imgSrc);
					dataJSON.put("price", random.nextInt(200));
					dataJSON.put("weight", random.nextInt(100));
					goodsArr.add(dataJSON);
					count ++ ;
				} catch (Exception e)
				{
					
				} 
			}
			resultJSON.put("goodsList", goodsArr);
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("请求商品列表报错:",e);
		}
		return resultJSON ; 
	}
	
	public static void main(String[] args)
	{
		JdSplider jdSplider = new JdSplider();
		JSONObject resultJSON = jdSplider.goodsList("",0);
		System.out.println(resultJSON);
	}
}
